#!/usr/bin/env python
from graph.Genedge import Genedge
from io.GenInput import GenInput
import os


class GenOutput:
    
    #path = os.path.abspath(__file__).strip()[:-15]
    path = os.getcwd()

    def spit_grammar(self, grapho, file):
        """
        Outputs a CFA grammar file from a graph
        """
        
        if not os.path.exists(self.path + "/output"):
            os.makedirs(self.path + "/output")
        
        os.chdir(self.path + "/output")       
        
        f = open(file, 'w')
        f.write('startshape ' + str(grapho.startshape) + '\n')
        if grapho.has_background():
            f.write('background { ')
            for param in grapho.background:
                f.write(param + ' ')
            f.write('} \n')
        
        for node in grapho.nodes_iter():
            if node != "SQUARE" and node != "CIRCLE":
                for instance in grapho[node].instances.iterkeys():
                    f.write('rule ' + node + ' {\n')
                    for rule in grapho[node].instances[instance]:
                        f.write(rule[0] + ' { ') 
                        for param_t in rule[1].params:
                            for param in param_t:
                                f.write(str(param) + ' ')
                        f.write(' }\n')
                    f.write(' }\n')
        os.chdir(self.path)

    def get_path(self):
        return self.path

def spit_grammar_to_str(grapho):
    f = ''.join('startshape ' + str(grapho.startshape) + '\n')
    if grapho.has_background():
        f = f.join('background { ')
        for param in grapho.background:
            f = f.join(param + ' ')
        f = f.join('} \n')
    
    for node in grapho.nodes_iter():
        if node != "SQUARE" and node != "CIRCLE":
            for instance in grapho[node].instances.iterkeys():
                f = f.join('rule ' + node + ' {\n')
                for rule in grapho[node].instances[instance]:
                    f = f.join(rule[0] + ' { ')
                    for param_t in rule[1].params:
                        for param in param_t:
                            f = f.join(str(param) + ' ')
                    f = f.join(' }\n')
                f = f.join(' }\n')
    return f
